import 'package:safetymonitor/app/components/custom_select_function.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/department_user_entity.dart';
import 'package:safetymonitor/app/data/entities/application/get_dict_all_entity.dart';
import 'package:safetymonitor/app/data/entities/home/execute_entity.dart';
import 'package:safetymonitor/router/app_pages.dart';

import '../core/core.dart';

///特殊作业-自定义人员选择样式控件
///[title] 标题
///[onCallBack] 选择回调
///[dataList] 已有的数据列表
///[isRequired] 是否必填
///[hintText] 提示文字
///[operatorType] 人员类型 作业人类型 0：作业实施人 1：作业负责人 2：监护人 3:编制人 4：司索人 5:指挥人 6：用电人 7：安全交底人 8：接受交底人 9：验收人
///[isEnabled] 是否可编辑
///[queryParameters] 请求人员数据的参数
/// demo:
/// ``` dart
/// CustomSelectWorkUserPage(
///   title: '标题',
///   onCallBack:(List<ExecuteTicketReceiptListOperatorLists> list){}
/// );
/// ```
class CustomSelectWorkUserPage extends StatefulWidget {
  const CustomSelectWorkUserPage({
    required this.title, //人员
    required this.titleType, //班次类型
    required this.onCallBack,
    this.dataList,
    this.isRequired = true,
    super.key,
    this.hintText,
    this.operatorType,
    this.isEnabled = true,
    this.queryParameters = const {},
  });

  final String title;
  final String titleType;
  final Function(List<ExecuteTicketReceiptListOperatorLists> list) onCallBack;
  final List<ExecuteTicketReceiptListOperatorLists>? dataList;
  final bool isRequired;
  final String? hintText;
  final int? operatorType;
  final bool isEnabled;
  final Map<String, dynamic> queryParameters;

  @override
  State<CustomSelectWorkUserPage> createState() =>
      _CustomSelectWorkUserPageState();
}

class _CustomSelectWorkUserPageState extends State<CustomSelectWorkUserPage> {
  List<ExecuteTicketReceiptListOperatorLists> dateList = [];
  static List<GetDictAllEntity> currencyState = [];

  @override
  initState() {
    super.initState();
    initCurrencyState();
    _initDate();
  }

  void initCurrencyState() {
    currencyState.clear();
    final GetDictAllEntity getDictAllEntity = GetDictAllEntity();
    getDictAllEntity.id = '1';
    getDictAllEntity.dictionaryLabel = '日常';
    currencyState.add(getDictAllEntity);
    final GetDictAllEntity getDictAllEntity2 = GetDictAllEntity();
    getDictAllEntity2.id = '2';
    getDictAllEntity2.dictionaryLabel = '应急';
    currencyState.add(getDictAllEntity2);
    final GetDictAllEntity getDictAllEntity3 = GetDictAllEntity();
    getDictAllEntity3.id = '3';
    getDictAllEntity3.dictionaryLabel = '安防';
    currencyState.add(getDictAllEntity3);
    final GetDictAllEntity getDictAllEntity4 = GetDictAllEntity();
    getDictAllEntity4.id = '4';
    getDictAllEntity4.dictionaryLabel = '门岗';
    currencyState.add(getDictAllEntity4);
  }

  /// 初始化数据
  void _initDate() {
    //添加数据
    if (widget.dataList != null && widget.dataList!.isNotEmpty) {
      dateList = widget.dataList!;
    }
    //是否包含指定人员
    bool haveOperator = false;
    for (var item in dateList) {
      if (item.operatorType == (widget.operatorType ?? 0)) {
        haveOperator = true;
        break;
      }
    }
    //如果为空则添加一个空数据
    if (dateList.isEmpty || !haveOperator) {
      dateList.add(ExecuteTicketReceiptListOperatorLists()
        ..operatorType = (widget.operatorType ?? 0));
    }
    setState(() {});
  }

  ///获取作业人信息
  Widget _getOperatorView(
      ExecuteTicketReceiptListOperatorLists item, int index) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 7.w),
      padding: EdgeInsets.symmetric(horizontal: 18.w, vertical: 14.w),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F7F7),
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        children: [
          //值班人员
          _getPersonnelSelection(item, index),
          AppGaps.vGap20,
          Divider(
            height: 1.w,
            color: const Color(0xFFE6E7EB),
          ),
          AppGaps.vGap20,
          //班次类型
          _getPersonnelSelectionTwo(item, index),
        ],
      ),
    );
  }

  ///获取人员选择样式
  Widget _getPersonnelSelection(
      ExecuteTicketReceiptListOperatorLists item, int index) {
    return Row(
      children: [
        Text(
          '*',
          style: TextStyle(
            fontSize: 14.sp,
            height: 1.2,
            color: AppColors.meaning_color_danger,
          ),
        ),
        Text(
          widget.title,
          style: TextStyle(
            fontSize: 14.sp,
            height: 1.1,
            color: AppColors.font_color_black,
          ),
        ),
        AppGaps.hGap20,
        Expanded(
            child: item.operatorUserName!.isNotEmpty
                ? Text(
                    item.operatorUserName ?? '',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      fontSize: 14.sp,
                      height: 1.2,
                      color: const Color(0xFF262F38),
                    ),
                  )
                : Text(
                    widget.isEnabled ? widget.hintText ?? '请选择' : '暂无',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      fontSize: 14.sp,
                      height: 1.2,
                      color: AppColors.text_grey,
                    ),
                  )),
        Visibility(
            visible: widget.isEnabled,
            child: Row(
              children: [
                AppGaps.hGap6,
                Icon(Icons.arrow_forward_ios,
                    size: 14.sp, color: AppColors.text_grey)
              ],
            )),
      ],
    ).clickOnce(() {
      FocusScope.of(context).unfocus();
      if (!widget.isEnabled) {
        return;
      }
      //第一种方式
      Get.toNamed(Routes.personnelDepartmentTreePage, arguments: {
        'queryParameters': widget.queryParameters,
        'title':UserManager.getUserCompanyName(),
        'isRadio': true,
      })?.then((value) {
        //如果不为空则设置人员信息
        if (value != null) {
          final List<DepartmentUserEntity> personList =
              value as List<DepartmentUserEntity>;
          item.operatorUserId = personList[0].getId();
          item.operatorUserName = personList[0].getShowName();
          item.phone = personList[0].mobile ?? '';
          _callBack();
          setState(() {});
        }
      });
      //第二种方式  主公司显示所有部门
      // Get.toNamed(Routes.selectPeople,arguments: {'tittle':UserManager.getUserCompanyName()})?.then((value) {
      //   if (value != null && value is UserRespEntity) {
      //     item.operatorUserId = value.getId();
      //     item.operatorUserName = value.getShowName();
      //     item.phone = value.mobile ;
      //     _callBack();
      //     setState(() {});
      //   }
      // });
      //第三种方式  主公司不显示所有部门
      // Get.toNamed(Routes.dutySelectPeople)?.then((value) {
      //   if (value != null && value is UserRespEntity) {
      //     item.operatorUserId = value.getId();
      //     item.operatorUserName = value.getShowName();
      //     item.phone = value.mobile ?? '';
      //     _callBack();
      //     setState(() {});
      //   }
      // });
    });
  }

  ///获取人员选择样式
  Widget _getPersonnelSelectionTwo(
      ExecuteTicketReceiptListOperatorLists item, int index) {
    return Row(
      children: [
        Text(
          '*',
          style: TextStyle(
            fontSize: 14.sp,
            height: 1.2,
            color: AppColors.meaning_color_danger,
          ),
        ),
        Text(
          widget.titleType,
          style: TextStyle(
            fontSize: 14.sp,
            height: 1.1,
            color: AppColors.font_color_black,
          ),
        ),
        AppGaps.hGap20,
        Expanded(
            child: item.operatorUserSign!.isNotEmpty
                ? Text(
                    item.operatorUserSign ?? '',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      fontSize: 14.sp,
                      height: 1.2,
                      color: const Color(0xFF262F38),
                    ),
                  )
                : Text(
                    widget.isEnabled ? widget.hintText ?? '请选择' : '暂无',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      fontSize: 14.sp,
                      height: 1.2,
                      color: AppColors.text_grey,
                    ),
                  )),
        Visibility(
            visible: widget.isEnabled,
            child: Row(
              children: [
                AppGaps.hGap6,
                Icon(Icons.arrow_forward_ios,
                    size: 14.sp, color: AppColors.text_grey)
              ],
            )),
      ],
    ).clickOnce(() {
      FocusScope.of(context).unfocus();
      if (!widget.isEnabled) {
        return;
      }
      //班次类型的选择
      selectCurrencyLevelType(item);
    });
  }

  ///状态
  void selectCurrencyLevelType(ExecuteTicketReceiptListOperatorLists item) {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '状态',
      dataList: currencyState,
      // checkedList: [GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        item.ticketPlanId = value[0].getId();
        item.operatorUserSign = value[0].getShowName();
        _callBack();
        setState(() {});
      },
    );
  }

  ///回调给外部
  void _callBack() {
    widget.onCallBack(dateList);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 12.w),
            child: Row(
              children: [
                // SvgPicture.asset(
                //   AppImages.icon_title,
                //   width: 20.w,
                //   height: 20.w,
                // ),
                // AppGaps.hGap6,
                Text(
                  '${widget.title}信息',
                  style: TextStyle(
                      color: const Color(0xff262F38),
                      height: 1.2,
                      fontWeight: FontWeight.w500,
                      fontSize: 14.sp),
                ),
                const Spacer(),
                Visibility(
                    visible: widget.isEnabled,
                    child: Text(
                      '添加人员',
                      style: TextStyle(
                          color: const Color(0xff5C6DFF),
                          height: 1.2,
                          fontWeight: FontWeight.w400,
                          fontSize: 12.sp),
                    ).clickOnce(() {
                      dateList.add(ExecuteTicketReceiptListOperatorLists()
                        ..operatorType = widget.operatorType ?? 0);
                      // AppToast.showSuccess('添加成功!');
                      setState(() {});
                    })),
              ],
            ),
          ),
          // Container(
          //   color: const Color(0xFFF5F7FC),
          //   height: 1.w,
          // ),
          ListView.separated(
            itemCount: dateList.length,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              final item = dateList[index];
              //  只显示传入的类型
              if (item.operatorType != (widget.operatorType ?? 0)) {
                return Container();
              }
              return Container(
                alignment: Alignment.center,
                child: Stack(
                  alignment: Alignment.topRight,
                  children: [
                    //获取人信息
                    _getOperatorView(item, index),
                    //删除按钮
                    Visibility(
                        visible: widget.isEnabled,
                        child: const Icon(
                          Icons.highlight_remove,
                          color: Color(0xFFFD6B6B),
                        ).clickOnce(() {
                          dateList.remove(item);
                          _callBack();
                          setState(() {});
                        }))
                  ],
                ),
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              if (dateList[index].operatorType != (widget.operatorType ?? 0)) {
                return Container();
              }
              return AppGaps.vGap8;
            },
          ),
          AppGaps.vGap12,
        ],
      ),
    );
  }
}
